import 'dart:async';

import 'package:basic_common/common_exports.dart';
import 'package:basic_common/global_getx.dart';
import '../modle/patient_msg_list_data.dart';

class MsgListController extends GetxController {
  RefreshController refreshController = RefreshController(initialRefresh: true);
  final patientList = <PatientMsgData?>[].obs;
  Timer? mTimer;
  @override
  void onInit() {
    onRefresh();
    mTimer = Timer.periodic(Duration(seconds: 3), (timer) {
         pageNo = 1;
      getMsgList();
    });
    super.onInit();
  }

  int pageSize = 10;
  int pageNo = 1;

  /// 下拉刷新
  onRefresh() async {
    pageNo = 1;
    patientList.value=[];
    await getMsgList();
  }

  /// 上拉加载
  onLoading() async {
    pageNo += 1;
    await getMsgList();
  }

  /// 患者消息列表
  getMsgList() async {
    String docNo = globalGetx.doctorNo.value;
    if (docNo.isEmpty) {
      ToastUtils.toast("医生信息获取失败");
      return;
    }
    String appUrl ="${HttpOptions.BASE_URL}${HttpUrl.PATIENT_MSG_LIST}?pageSize=${pageSize}&pageNo=${pageNo}";
    HttpData res = await ApiService()
        .getPatientMsgList(data: {"doctorNo": docNo}, baseUrl: appUrl);
    if (res.code == 1) {
      PatientMsgListData listData = PatientMsgListData.fromJson(res.toJson());
      print(
          "length====${listData.data!.list!.length}========pageNo===${pageNo}=======pageSize==${pageSize}");
      if (pageNo == 1) {
        patientList.value = listData.data!.list!;
      } else {
        patientList.value = [...patientList.value, ...listData.data!.list!];
      }
      if (listData.data!.list!.length < pageSize) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
      refreshController.refreshCompleted();
      update(['msgList']);
    } else {
      patientList.value = [];
      update(['msgList']);
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    // 移除生命周期监听
    mTimer!.cancel();
    mTimer = null;
    super.onClose();
  }
}
